//
//  productCenterVC.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/7.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "productCenterVC.h"
#import "productModel.h"
#import "childBaseTableViewCell.h"
#import "BPProductMakeViewController.h"
#import "AppDelegate.h"
#import "BPhttpTool.h"
#import "AccountTool.h"
#import "productModel.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "orderDetailVC.h"
#import "BPLoginViewController.h"

@interface productCenterVC ()<childBaseTableViewCellDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    BOOL _isfirst;
}

//未印刷数据
@property (nonatomic,strong)NSMutableArray *unfinuishArry;

//已印刷数据
//@property (nonatomic,strong)NSMutableArray *finishArry;

@property (nonatomic,strong)AppDelegate *delegate;

//数据源
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)UITableView *ProductTableView;

@property (nonatomic, assign) NSIndexPath *indePath;

@end

@implementation productCenterVC

- (void)viewWillAppear:(BOOL)animated
{
    [_delegate hiddenPreView];
    _unfinuishArry = [NSMutableArray array];
//    _finishArry = [NSMutableArray array];
    [self getOrderData];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

- (void)getOrderData
{
        // 网址解析不了 (跟数据 没关系)
        
//    [MBProgressHUD showMessage:@"加载中,请稍等..."];
    [BPhttpTool get:[NSString stringWithFormat:@"%@works/getlist/uid/%@",BPhttp,[AccountTool account].uid] params:nil success:^(id responseObj) {
        
        NSLog(@"alldata = %@", responseObj);
        
        if (responseObj == nil) {
            [self createKongOrder];
             
        }
        else{
            
            NSArray *arry = [productModel objectArrayWithKeyValuesArray:responseObj];
           
            for (productModel *cellModel in arry) {
                
                if ([cellModel.status intValue] == 1) {
                    
                    if ([myProductManger haveProduct:cellModel.iD]) {
                        cellModel.status = [NSString stringWithFormat:@"3"];
                    }
                    [self.unfinuishArry addObject:cellModel];
                   
                }else if ([cellModel.status intValue] == 2){
//                    [self.finishArry addObject:cellModel];
                }else{
                    BPLog(@"%@",cellModel.status);
                }
            }
            if (_isfirst == YES) {
                _isfirst = NO;
                
                // 判断 数组 是不是 空的!  然后 显示不同的 界面
                if (self.unfinuishArry.count == 0) {
                    [self createKongOrder];
                }
                else{
                    self.dataArray = self.unfinuishArry;
                    [self.ProductTableView reloadData];
                    
                    NSLog(@"self.dataArray = %@", self.dataArray);
                    NSLog(@"self.unfinuishArry = %@", self.unfinuishArry);
                }
            }
        }
       [MBProgressHUD hideHUD];
    
    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"加载失败!"];
        BPLog(@"获取失败");
        NSLog(@"失败");
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    myProductManger = [[CoreDateManager alloc] init];
    self.dataArray = [NSMutableArray array];
    _delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    
    [self setUpTableView];
    
    //[self addTopButton];
    _isfirst = YES;
    
    [self creat];
   
}

- (void)creat{
    CGFloat imX = 20;
    CGFloat imY = 30;
    CGFloat imW = 20;
    CGFloat imH = 20;
    
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(imX, imY, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *top = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, imW, imH)];
    //    top.image = [UIImage imageNamed:@"返回"];
    [top setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [top addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:top];
    
    CGFloat laX = self.view.frame.size.width / 2 - 50;
    CGFloat laW = 100;
    CGFloat laH = 40;
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(laX, imY - 10, laW, laH)];
    name.text = @"我的作品";
    name.font = [UIFont systemFontOfSize:21];
    name.textColor = BPFenHongColor;
    [self.view addSubview:name];
    
    
    UIImageView *longL = [[UIImageView alloc] initWithFrame:CGRectMake(0, imY + 30, self.view.frame.size.width, 5)];
    longL.image = [UIImage imageNamed:@"波纹线"];
    [self.view addSubview:longL];
}


// 如果 返回的数据为空的话
- (void)createKongOrder{
    
    CGFloat imX = 20;
    CGFloat imY = 30;
    CGFloat imW = 20;
    CGFloat imH = 20;
    
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(imX, imY, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *top = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, imW, imH)];
    //    top.image = [UIImage imageNamed:@"返回"];
    [top setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [top addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:top];
    
    CGFloat laX = self.view.frame.size.width / 2 - 50;
    CGFloat laW = 100;
    CGFloat laH = 40;
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(laX, imY - 10, laW, laH)];
    name.text = @"我的作品";
    name.font = [UIFont systemFontOfSize:21];
    name.textColor = BPFenHongColor;
    [self.view addSubview:name];
    
    
    CGFloat ImX = self.view.frame.size.width / 2 - 100.0f;
    CGFloat ImY = 130.0f;
    CGFloat ImW = ImX + 120.0f;
    CGFloat ImH = ImX + 120.0f;
    
//    UIImageView *longL = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 5)];
//    longL.image = [UIImage imageNamed:@"波纹线"];
//    [self.view addSubview:longL];
    
    
    UIImageView *images = [[UIImageView alloc]initWithFrame:CGRectMake(ImX + 10.0f, ImY, ImW, ImH)];
    images.image = [UIImage imageNamed:@"logoKong"];
    [self.view addSubview:images];
    
    CGFloat LabH = 40.0f;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ImX - 10.0f, ImY + ImH + 50.0f, ImW + 50.0f, LabH)];
    label.text = @"您还没有作品 , 赶紧去定制一个吧~";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:13];
    label.alpha = 0.5;
    [self.view addSubview:label];
    
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(ImX + 10.0f, ImY + ImH + 110.0f, ImW, LabH)];
    button.backgroundColor = BPGlobaThemeColor;
    [button setTitle:@"马上制作" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.layer.cornerRadius = 20;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)button:(UIButton *)button{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (void)setUpTableView{
    CGFloat tableViewY = BPScreenNavY + 50.0f;
//    UITableView *ProductTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableViewY, BPScreenW, BPScreenH - tableViewY)];
     UITableView *ProductTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableViewY - 50.0f, BPScreenW, BPScreenH - BPScreenNavY)];
    ProductTableView.backgroundColor = [UIColor whiteColor];
    ProductTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    ProductTableView.delegate = self;
    ProductTableView.dataSource = self;
    [self.view addSubview:ProductTableView];
    self.ProductTableView = ProductTableView;
}

// 头部的 "未印刷作品" 和 "已保存印刷" 已经去掉了(下面的tableView的位置向上移动了)
//- (void)addTopButton
//{
//    NSArray *buttonName = [NSArray arrayWithObjects:@"未印刷作品",@"已保存印刷", nil];
//    for (int i = 0; i < 2; i ++) {
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        BPLineView *line = [[BPLineView alloc] initWithFrame:CGRectMake(0, 0, 1, btn.height)];
//        btn.tag = 1000+i;
//        CGFloat btnW = BPScreenW / 2.0;
//        btn.frame = CGRectMake(btnW * i, 0, btnW, self.headView.height);
//        if (i == 1) {
//            line.frame = CGRectMake(btnW, 10, 1, btn.height - 20);
//            
//        }
//
//        [btn setTitle:buttonName[i] forState:UIControlStateNormal];
//        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        btn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
//        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
//        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.headView addSubview:btn];
//        [self.headView addSubview:line];
//    }
//}


// 不走了
//top按钮点击事件
//- (void)btnClick:(UIButton *)button
//{
//    //self.dataArray = [NSMutableArray array];
//    if (button.tag == 1000) {
//        self.dataArray = self.unfinuishArry;
//        [self.ProductTableView reloadData];
//        
//    }else {
//        self.dataArray = self.finishArry;
//        [self.ProductTableView reloadData];
//    }
//}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    childBaseTableViewCell *cell = [childBaseTableViewCell cellWithTableView:tableView];
    
    cell.delegate = self;
    
    [cell setUpCell:self.unfinuishArry[indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self lookDetail:[self.ProductTableView cellForRowAtIndexPath:indexPath]];
}


// 继续编辑
- (void)continueDIY:(childBaseTableViewCell *)childBaseCell
{
    NSIndexPath *indexPath = [self.ProductTableView indexPathForCell:childBaseCell];
    productModel *model = self.dataArray[indexPath.row];
    BPProductDetail *productInfo = [myProductManger getOneMyProduct:model.iD];
    NSMutableArray *assetArry = [NSMutableArray array];
    
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred,
                  ^{
                      library = [[ALAssetsLibrary alloc] init];
                  });
    
    for (BPProductDetailPage *pages in productInfo.pages) {
        for (BPProductModel *models in pages.moulds) {
            if (models.type == 0) {
                NSURL *assetURl = [NSURL URLWithString:models.alassetStr];
                //重相册库中获取照片
                [library assetForURL:assetURl resultBlock:^(ALAsset *asset) {
                    if (asset == nil) {
                        [assetArry addObject:@"noAsset"];
                    }else{
                        [assetArry addObject:asset];
                    }
                    if (assetArry.count == productInfo.picnum) {
                        _delegate.isEdit = YES;
                        BPProductMakeViewController *DIY = [[BPProductMakeViewController alloc] init];
                        DIY.isFirst = NO;
                        DIY.productInfo = productInfo;
                        DIY.alassetArry = assetArry;
                        [self.navigationController pushViewController:DIY animated:YES];
                    }
                } failureBlock:^(NSError *error) {
                    NSLog(@"dddd");
                }];
            }
        }
    }
}

- (void)shanchuCell:(childBaseTableViewCell *)childBaseCell
{
   
    NSIndexPath *indexPath = [self.ProductTableView indexPathForCell:childBaseCell];
    
    productModel *model = self.dataArray[indexPath.row];
    int workID = [model.iD intValue];
    if (workID != 0) {
        [MBProgressHUD showMessage:@"正在删除"];
        [BPhttpTool get:[NSString stringWithFormat:@"%@works/delete/id/%d",BPhttp,workID] params:nil success:^(id responseObj) {
            NSDictionary *dic = responseObj;
            if ([dic[@"status"] intValue] == 1) {
                
                [self.dataArray removeObjectAtIndex:indexPath.row];
                NSLog(@"~~~~%@", self.dataArray);
                [MBProgressHUD showSuccess:@"删除成功"];
                
                [self.ProductTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                //    [self.dataArray removeObjectAtIndex:indexPath.row];
                
//                     [self.ProductTableView reloadData];
                if (self.dataArray.count == 0) {
                    [self createKongOrder];
                }
                
            }
        } failure:^(NSError *error) {
            
        }];
        [MBProgressHUD hideHUD];
        [myProductManger deletOneProduct:model.iD];
    }
    
}

- (void)goToPrint
{
    BPLog(@"点击了马上印刷");
}

// 点击 进入详情页面
- (void)lookDetail:(childBaseTableViewCell *)childBaseCell
{
    
    NSIndexPath *indexPath = [self.ProductTableView indexPathForCell:childBaseCell];
    cellBaseModel *model = self.dataArray[indexPath.row];
     productModel *modelS = self.dataArray[indexPath.row];
    int workID = [model.iD intValue];
    if (workID != 0) {
        BPProductDetail *detailModel = [[BPProductDetail alloc] init];
        
        detailModel.title = model.title;
        detailModel.workID = model.iD;
        detailModel.iD = model.product_id;
        detailModel.category = model.category;
        detailModel.xiaoguo = model.picture;
        detailModel.finalPrice = @"0";
        detailModel.price = model.price;
        detailModel.oprice = model.oprice;
        
        //取出产品中每页的信息，转化成对象放在数组
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"pages"] == nil) {
            [MBProgressHUD showError:@"此作品不能被编辑了!"];
            
        }else{
            
            detailModel.pages =  [BPProductDetailPage objectArrayWithKeyValuesArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"pages"]];
        }
        
        BPProductDetail *productInfo = [myProductManger getOneMyProduct:modelS.iD];
        
        // 后添加的
        for (BPProductDetailPage *page in detailModel.pages) {
            if (![page.moulds isKindOfClass:[NSNull class]] && page.moulds != nil) {
                page.moulds = [BPProductModel objectArrayWithKeyValuesArray:page.moulds];
            }
        }
        
        orderDetailVC *orderVc = [[orderDetailVC alloc] init];
        orderVc.webName = @"lookDetail.html";
        orderVc.title = @"作品详情";
        orderVc.productModel = detailModel;
        orderVc.model = modelS;
        orderVc.modelPro = productInfo;
        orderVc.isF = YES;
        [self.navigationController pushViewController:orderVc animated:YES];
    }
}


/* 2. 指定TableView那些行可以编辑 */
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

/* 4. 确定编辑, (先操作数据, 在操作UI(cell)) */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.indePath = indexPath;
    
    NSLog(@"第几行 = %ld", indexPath.row);
    
    /* 1. 删除操作 */
    /* 判断当前的编辑类型是否为 删除 */
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        /* 1. 删除数据源 */
//        [self.unfinuishArry removeObjectAtIndex:indexPath.row + 1];
       // [self.unfinuishArry removeObjectAtIndex:0];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您真的要删除此作品吗?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
//        [self shanchuCell:[self.ProductTableView cellForRowAtIndexPath:indexPath]];
        
        /* 2. 删除 cell */
       // [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
   
//    /* 2. 插入操作 */
//    if (editingStyle == UITableViewCellEditingStyleInsert) {
//        
//        /* 1. 数据操作 */
//        [self.unfinuishArry insertObject:@"123456" atIndex:indexPath.row];
//        
//        /* 2. cell 操作 */
//        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        
        [self shanchuCell:[self.ProductTableView cellForRowAtIndexPath:self.indePath]];
    }
    else{
        
        [alertView removeFromSuperview];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
